//
//  QTHistoryProductTableViewController.m
//  qdqts
//
//  Created by centling on 14-6-21.
//  Copyright (c) 2014年 seas.cheng. All rights reserved.
//

#import "QTHistoryProductTableViewController.h"
#import "scanHistoryCell.h"
#import "Global.h"
//#import "QTProductHistoryElement.h"
#import "UIImageView+UIActivityIndicatorForSDWebImage.h"
#import "QTProductDetailViewController.h"

#import "Product.h"
#import "QTProductPersistence.h"

@interface QTHistoryProductTableViewController ()

@end

@implementation QTHistoryProductTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title=@"历史记录";
    //添加右按钮
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash                                 target:self action:@selector(RemoveElement)];
    self.navigationItem.rightBarButtonItem = rightButton;
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.hidenTabBarDelegate hideTabBar:NO];
    //-----------------------Persistence---------------------
    QTProductPersistence *persistence=[[QTProductPersistence alloc] init];
    self.productHistory=[persistence getHistory];
    NSLog(@"getHistory:%@",self.productHistory);
       //-----------------------------------------------------------
    
    if ([self.productHistory count] == 0) {
        self.navigationItem.rightBarButtonItem.enabled = NO;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        UILabel  *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 100,300,150)];
        label.text= @"历史记录为空!";
        //        //背景颜色为红色
        //        label.backgroundColor = [UIColor redColor];
        //设置字体颜色为白色
        label.textColor = [UIColor blackColor];
        //文字居中显示
        label.textAlignment = UITextAlignmentCenter;
        //自动折行设置
        label.lineBreakMode = UILineBreakModeWordWrap;
        label.numberOfLines = 0;
        label.tag =1000;
        //        //设置字体
        //        label.font = [UIFont fontWithName:@"Arial-BoldItalicMT" size:32];
        [self.view addSubview:label];
    }
    else
    {
        self.navigationItem.rightBarButtonItem.enabled = YES;
        for (UIView* view in self.view.subviews) {
            if (view.tag == 1000 ) {
                [view removeFromSuperview];
            }
        }
        [self.tableView reloadData];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    NSInteger t = [self.productHistory count];
    NSLog(@"%d   history array count",t);
    return [self.productHistory count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *scanCell = @"scanCell";
    scanHistoryCell *cell = (scanHistoryCell *)[tableView dequeueReusableCellWithIdentifier:scanCell];
    
    if (cell ==nil) {
        NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"scanHistoryCell" owner:self options:nil];
        cell = (scanHistoryCell *)[nibArray objectAtIndex:0];
    }
    cell.productName.text = ((Product *)[self.productHistory objectAtIndex:indexPath.row]).productName;
    //获得系统日期
    NSDate *  senddate=((Product *)[self.productHistory objectAtIndex:indexPath.row]).date;
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd"];
    cell.scanTime.text = [dateformatter stringFromDate:senddate];
    
    NSString *imageUrl=((Product *)[self.productHistory objectAtIndex:indexPath.row]).filePath;
    NSURL *url=[NSURL URLWithString:[self convertPicURL:imageUrl]];
    NSLog(@"imageURI:%@",url);
    [cell.productImage setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
        if (image == nil) {
            [cell.productImage setImage:[UIImage imageNamed:@"暂无图片.png"]];
        }
    } usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray ];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    NSLog(@"puid:%@",((Product *)[self.productHistory objectAtIndex:indexPath.row]).puid);
    return cell;

}


//Set the height of the cell
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{
    return 85;
}


-(void)RemoveElement
{

        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
                                                      message:[NSString stringWithFormat:@"确定要清空历史记录？",nil]
                                                     delegate:self
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:@"取消", nil];

        [alert show];
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0) {
        QTProductPersistence *persistence=[[QTProductPersistence alloc] init];
        [persistence deleteHistory];
        [self viewWillAppear:YES];
        [self.tableView reloadData];
        
    }
    
}
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    QTProductDetailViewController* productDetailViewController = [[QTProductDetailViewController alloc ] init];
    productDetailViewController.puid=((Product *)[self.productHistory objectAtIndex:indexPath.row]).puid;
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:nil action:nil];
    self.navigationController.navigationBar.tintColor=[UIColor whiteColor];
    [self.navigationItem setBackBarButtonItem:backItem];
    [self.hidenTabBarDelegate hideTabBar:YES];
    [self.navigationController pushViewController:productDetailViewController animated:YES];
    
}

-(NSString *)convertPicURL:(NSString *)url
{
    NSString *picURL=url;
    NSRange range_http = [url rangeOfString:@"http:"];
    NSRange range_HTTP = [url rangeOfString:@"HTTP:"];
    if ((range_http.length==0)&&(range_HTTP.length==0)) {
        picURL=[qsServerUrl stringByAppendingString:url==nil?@"":url];
    }
    return  picURL;
}



@end
